<script setup>
  import { onBeforeUnmount, onMounted, ref } from 'vue'
  import { Calendar, Clock, Delete, Document, Link, Share } from '@element-plus/icons-vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { cancelShareService, shareListService } from '@/api/share.js'

  const shareList = ref([])

  // 右键菜单相关的响应式变量
  const showContextMenu = ref(false)
  const contextMenuX = ref(0)
  const contextMenuY = ref(0)
  const selectedFile = ref(null)

  const isLoading = ref(true)

  // 获取分享文件列表
  const getShareList = async () => {
    isLoading.value = true
    try {
      const res = await shareListService()
      shareList.value = res.data
    } catch (error) {
      console.error(error)
    } finally {
      isLoading.value = false
    }
  }

  // 处理复制分享链接
  const handleCopyShareLink = file => {
    try {
      // 创建临时输入元素
      const tempInput = document.createElement('input')
      tempInput.value = file.shareUrl
      tempInput.style.position = 'absolute'
      tempInput.style.left = '-9999px'
      document.body.appendChild(tempInput)

      // 选中并复制
      tempInput.select()
      document.execCommand('copy')
      // 移除临时元素
      document.body.removeChild(tempInput)
      return true
    } catch (error) {
      console.error('复制失败:', error)
      return false
    }
  }

  // 处理取消分享
  const handleCancelShare = async files => {
    const shareIds = files.map(file => file.shareId)
    console.log(shareIds)
    await cancelShareService(shareIds)
    ElMessage.success(files.length > 1 ? '已批量取消分享' : '已取消分享')
    // 清空选择
    multipleSelection.value = []
    tableRef.value?.clearSelection()
    // 刷新列表
    await getShareList()
  }

  // 确认取消分享对话框
  const handleCancelShareConfirm = async files => {
    hideContextMenu()
    try {
      await ElMessageBox.confirm(
        files.length > 1
          ? `确认取消这 ${files.length} 个文件的分享？`
          : `确认取消 "${files[0].shareName}" 的分享？`,
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      await handleCancelShare(files)
    } catch {
      // 用户取消操作
    }
  }

  // 处理右键点击事件
  const handleContextMenu = (row, column, event) => {
    event.preventDefault()

    const isSelected = multipleSelection.value.some(item => item.shareId === row.shareId)

    if (!isSelected) {
      multipleSelection.value = []
      tableRef.value?.clearSelection()
      tableRef.value?.toggleRowSelection(row, true)
      multipleSelection.value = [row]
    }

    selectedFile.value = row
    showContextMenu.value = true
    contextMenuX.value = event.clientX
    contextMenuY.value = event.clientY
  }

  // 处理菜单项点击
  const handleMenuClick = async action => {
    switch (action) {
      case 'copy':
        await handleCopyShareLink(selectedFile.value)
        break
      case 'cancel':
        await handleCancelShareConfirm(
          multipleSelection.value.length > 0 ? multipleSelection.value : [selectedFile.value]
        )
        break
    }
    hideContextMenu()
  }

  // 隐藏右键菜单
  const hideContextMenu = event => {
    if (event && event.target.closest('.context-menu')) {
      return
    }
    showContextMenu.value = false
    selectedFile.value = null
  }

  const multipleSelection = ref([])
  const handleSelectionChange = val => {
    multipleSelection.value = val
  }

  const tableRef = ref(null)
  const handleRowClick = (row, column) => {
    if (column.type === 'selection') return

    multipleSelection.value = []
    tableRef.value?.clearSelection()

    tableRef.value?.toggleRowSelection(row, true)
    multipleSelection.value = [row]
  }

  // 有效期换算
  const calculateDaysRemaining = endTimeStr => {
    // 解析结束时间
    const endTime = new Date(endTimeStr)
    const now = new Date()

    // 计算时间差（毫秒）
    const timeDiff = endTime - now

    // 计算剩余天数（向上取整，保证即使不满一天也显示1天）
    const daysRemaining = Math.ceil(timeDiff / (1000 * 60 * 60 * 24))

    return daysRemaining > 0 ? daysRemaining : 0
  }

  onMounted(() => {
    getShareList()
    document.addEventListener('click', hideContextMenu)
  })

  onBeforeUnmount(() => {
    try {
      document.removeEventListener('click', hideContextMenu)
    } catch (error) {
      console.error('移除事件监听器时出错:', error)
    }
  })
</script>

<template>
  <div class="page page-share">
    <el-alert :closable="false" show-icon title="这里显示你分享的所有文件" type="info"></el-alert>
    <!-- 文件列表 -->
    <el-card class="file-box no-select" @contextmenu.prevent>
      <el-scrollbar height="500px">
        <el-table
          ref="tableRef"
          v-loading="isLoading"
          :data="shareList"
          :row-style="{ height: '40px' }"
          element-loading-background="rgba(255, 255, 255, 0.9)"
          element-loading-text="数据加载中..."
          style="width: 100%; margin-top: 18px; cursor: pointer"
          @row-contextmenu="handleContextMenu"
          @selection-change="handleSelectionChange"
          @row-click="handleRowClick"
          @contextmenu.prevent
        >
          <template #empty>
            <el-empty description="暂无分享文件" />
          </template>
          <el-table-column type="selection" width="30%" />
          <el-table-column align="center" label="分享名称" min-width="20%">
            <template #header>
              <div style="display: flex; align-items: center">
                <el-icon style="font-size: 16px; margin-right: 5px">
                  <Document />
                </el-icon>
                <span>分享名称</span>
              </div>
            </template>
            <template #default="scope">
              <div class="file-item">
                <span class="shareName">{{ scope.row.shareName }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="提取码" min-width="10%" prop="shareCode">
            <template #header>
              <div class="my-column">
                <el-icon style="font-size: 16px; margin-right: 5px">
                  <Link />
                </el-icon>
                <span>提取码</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="分享时间" min-width="15%" prop="createTime">
            <template #header>
              <div class="my-column">
                <el-icon style="font-size: 16px; margin-right: 5px">
                  <Clock />
                </el-icon>
                <span>分享时间</span>
              </div>
            </template>
          </el-table-column>
          <!--<el-table-column align="center" label="下载次数" min-width="10%" prop="downloadCount">-->
          <!--  <template #header>-->
          <!--    <div class="my-column">-->
          <!--      <el-icon style="font-size: 16px; margin-right: 5px">-->
          <!--        <Download />-->
          <!--      </el-icon>-->
          <!--      <span>下载次数</span>-->
          <!--    </div>-->
          <!--  </template>-->
          <!--</el-table-column>-->
          <!--<el-table-column align="center" label="预览次数" min-width="10%" prop="viewCount">-->
          <!--  <template #header>-->
          <!--    <div class="my-column">-->
          <!--      <el-icon style="font-size: 16px; margin-right: 5px">-->
          <!--        <View />-->
          <!--      </el-icon>-->
          <!--      <span>预览次数</span>-->
          <!--    </div>-->
          <!--  </template>-->
          <!--</el-table-column>-->
          <el-table-column align="center" label="有效期" min-width="10%" prop="shareEndTime">
            <template #header>
              <div class="my-column">
                <el-icon style="font-size: 16px; margin-right: 5px">
                  <Calendar />
                </el-icon>
                <span>有效期</span>
              </div>
            </template>
            <template #default="scope">
              <span v-if="scope.row.shareDayType === 0">永久分享</span>
              <span v-else> {{ calculateDaysRemaining(scope.row.shareEndTime) }} 天后失效 </span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="状态" min-width="10%" prop="shareStatus">
            <template #header>
              <div class="my-column">
                <el-icon style="font-size: 16px; margin-right: 5px">
                  <Share />
                </el-icon>
                <span>状态</span>
              </div>
            </template>
            <template #default="scope">
              <el-text v-if="scope.row.shareStatus === 0">分享正常</el-text>
              <el-text v-else-if="scope.row.shareStatus === 1" type="danger">分享失效</el-text>
              <el-text v-else-if="scope.row.shareStatus === 2">永久分享</el-text>
            </template>
          </el-table-column>
        </el-table>
      </el-scrollbar>
    </el-card>

    <!-- 右键菜单 -->
    <div
      v-show="showContextMenu"
      :style="{ top: contextMenuY + 'px', left: contextMenuX + 'px' }"
      class="context-menu no-select"
      @contextmenu.prevent
    >
      <template v-if="selectedFile">
        <div class="menu-item" @click="handleMenuClick('copy')">
          <el-icon>
            <Link />
          </el-icon>
          <span>复制链接</span>
        </div>
        <div class="menu-item" @click="handleMenuClick('cancel')">
          <el-icon>
            <Delete />
          </el-icon>
          <span>取消分享</span>
        </div>
      </template>
    </div>
  </div>
</template>

<style lang="less" scoped>
  @import '@/assets/variable.less';

  .el-table {
    position: relative;
    min-height: 200px;
  }

  .file-item {
    display: flex;
    align-items: center;
    width: 100%;

    .shareName {
      //margin-left: 10px;
      line-height: 24px;
    }
  }

  .page-share {
    height: 100%;
  }

  .file-box {
    max-height: 620px;
    position: relative;
    margin-top: 12px;
    padding: 20px;
    flex: 1;
    background-color: #fff;
  }
</style>
